package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.schema.MultiPartName;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class commonController {

    @Value("${Image.path}")
    private String BasePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("获取到得文件名:{}", file.getOriginalFilename());
        //获取原始图片名称
        String originalFilename = file.getOriginalFilename();
        //获取名称后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //通过UUID生成文件名
        String FileName = UUID.randomUUID().toString();
        FileName = FileName + suffix;
        File dir = new File(BasePath);
        //判断目录是否存在，不存在就创建
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(BasePath + FileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(FileName);
    }

    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse resp) {

        log.info("获取到得文件名称:{}", name);
        FileInputStream fis = null;
        ServletOutputStream ops = null;
        try {
            //输入流读取文件
            fis = new FileInputStream(BasePath + name);
            //获取输出流
            ops = resp.getOutputStream();
            //设置响应类型
            resp.setContentType("image/jpeg");
            //读取数据
            int len;
            byte[] bys = new byte[1024];
            while ((len = fis.read(bys)) != -1) {
                //向前端响应数据
                ops.write(bys, 0, len);
                ops.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ops!=null){
                try {
                    ops.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
